import amaret.freestyle.FreestyleC;
import FreestyleC.CoreC.Scheduler;
import FreestyleC.CoreC.System;

module App inherits amaret.freestyle.core.IProgram {

    proxy TimerMilli inherits embios.interfaces.ITimerMilli;
    proxy Led        inherits embios.interfaces.ILed;
    proxy Adc        inherits embios.interfaces.IAdc;

internal:
    
    Void reactorFxn( Ptr me, Scheduler.Signal sig );

    struct Module_State {
        Scheduler.Reactor reactor;
        Scheduler.Event sampleTimer;
        Scheduler.Event samplePrinter;
        UInt16 samples[5];
    }
}

implementation {

    final Scheduler.numPriorities := 1;
    
    TimerMilli := FreestyleC.BoardC.TimerMilli8BitTimer0;
    Led := FreestyleC.BoardC.Led0;
    Adc := FreestyleC.BoardC.Adc10Bit;
    
    function Module_State.init()
    {
        this.reactor.init_meta(0, reactorFxn);
        this.sampleTimer.init_meta(offsetof<Module_State.sampleTimer>, 0);
        this.samplePrinter.init_meta(offsetof<Module_State.samplePrinter>, 1);
        
        for (var Int i = 0; i < 5; i++) {
            this.samples[i] = 0;
        }
    }
    
    function reactorFxn( me, sig )
    {   
        if (sig == 0) {
            
            Adc.read(module.samples, 5, module.samplePrinter.toPostable()); 
            Led.toggle(); 
            
        } else if (sig == 1) {    
            
            for (var Int i = 0; i < 5; i++) {
                System.printf("%d\n", module.samples[i]);
            }
        }
    }
    
    function run()
    {   
        TimerMilli.start(1000, true, module.sampleTimer.toPostable());
  
        Scheduler.start();
    }

}
